package com.education.project.web.controller;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.education.project.model.WebUser;
import com.education.project.service.WebUserService;
import com.education.project.web.form.UpdatePwdForm;

@Controller
@RequestMapping("/user")
public class UserController {
	@Autowired
	private WebUserService webUserService;
	
	@RequestMapping("/index")
	public String getIndexPage(HttpSession session, ModelMap model) {
		return "index";
	}
	
	@GetMapping("/update_pwd")
	public String getUpdatePwdPage(ModelMap model) {
		UpdatePwdForm form = new UpdatePwdForm();
		model.addAttribute("form", form);
		return "update_pwd";
	}
	
	@PostMapping("/update_pwd")
	public String updatePwd(@Valid @ModelAttribute("form") UpdatePwdForm form,BindingResult binder,HttpSession session,ModelMap model) {
		if(!binder.hasErrors()) {
			if(!form.getPassword().equals(form.getConfirmPassword())) {
				binder.rejectValue("confirmPassword", "error", "确认密码输入错误");
			}
		}
		if(binder.hasErrors()) {
			return "update_pwd";
		}
		WebUser webUser = (WebUser) session.getAttribute("webUser");
		webUserService.updatePwd(webUser.getId(), form.getPassword());
		model.addAttribute("message", "更新成功");
		return "control_success";
	}
}
